package com.carleasoft.mps.forum.business.answer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carleasoft.mps.core.user.ThreadUserContext;
import com.carleasoft.mps.core.user.UserCacheData;
import com.carleasoft.mps.forum.business.answer.bean.ForumComment;
import com.carleasoft.mps.forum.business.answer.bean.ForumUserPermission;
import com.carleasoft.mps.forum.business.answer.bean.po.ForumUserPo;
import com.carleasoft.mps.forum.business.answer.mapper.ForumCommentMapper;
import com.carleasoft.mps.forum.business.answer.service.ForumCommentService;
import com.carleasoft.mps.forum.business.answer.service.ForumUserPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zang
 * @since 2023-05-09
 */
@Service
public class ForumCommentServiceImpl extends ServiceImpl<ForumCommentMapper, ForumComment> implements ForumCommentService {
    @Autowired
    private ForumUserPermissionService forumUserPermissionService;

    @Override
    public List<ForumComment> selForumComment(ForumComment forumComment) {
        List<ForumComment> res = this.list(new QueryWrapper<ForumComment>()
                        .orderByDesc("CREATE_TIME")
                .eq("ARTICLE_CODE", forumComment.getArticleCode())
                .eq("REPLY_CODE", "-1"));
        for (ForumComment re : res) {
            List<ForumComment> children = this.list(new QueryWrapper<ForumComment>()
                    .eq("ARTICLE_CODE", forumComment.getArticleCode())
                    .eq("REPLY_CODE", re.getCommentCode()));
            re.setChildren(children);
        }
        return res;
    }

    @Override
    public String saveForumComment(ForumComment forumComment) {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        ForumUserPermission forumUser = forumUserPermissionService.getOne(new QueryWrapper<ForumUserPermission>().eq("USER_CODE", user.getUserCode()), false);
        // 禁止发帖
        if(null != forumUser && forumUser.getIsReview() == 1) {
            return "您已被禁止评论";
        } else {
            forumComment.setCommentCode(UUID.randomUUID().toString());
            forumComment.setCreatePersonCode(user.getUserCode());
            forumComment.setCreatePersonName(user.getUserName());
            forumComment.setCreateTime(new Date());
            this.save(forumComment);
            return "提交成功";
        }
    }

    @Override
    public Page<ForumComment> pageForumComment(Page page, ForumUserPo forumUserPo) {
        Page<ForumComment> res = this.getBaseMapper().pageForumComment(page,forumUserPo);
        return res;
    }
}
